package org.dromara.learning_lhz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.learning_lhz.entity.AsModuleEntity;
import org.dromara.learning_lhz.entity.AsOptionAnswerEntity;
import org.dromara.learning_lhz.entity.AsStudyQuestionsEntity;
import org.dromara.learning_lhz.entity.dto.AsStudyQuestionsDto;
import org.dromara.learning_lhz.mapper.ModuleMapper;
import org.dromara.learning_lhz.mapper.OptionAnswerMapper;
import org.dromara.learning_lhz.mapper.StudyQuestionsMapper;
import org.dromara.learning_lhz.service.ModuleService;
import org.dromara.learning_lhz.service.OptionAnswerService;
import org.dromara.learning_lhz.service.StudyQuestionsService;
import org.flowable.engine.impl.persistence.entity.ModelEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class StudyQuestionsServiceImpl extends ServiceImpl<StudyQuestionsMapper, AsStudyQuestionsEntity> implements StudyQuestionsService {
    @Autowired
    private OptionAnswerService optionAnswerService;
    @Autowired
    private StudyQuestionsMapper studyQuestionsMapper;
    @Autowired
    private OptionAnswerMapper optionAnswerMapper;
    @Autowired
    private ModuleMapper moduleMapper;

    @Override
    public List<AsStudyQuestionsEntity> selQuestions(AsStudyQuestionsEntity asStudyQuestionsEntity) {
        // 1. 查询题目列表
        LambdaQueryWrapper<AsStudyQuestionsEntity> questionQueryWrapper = new LambdaQueryWrapper<>();

        // 根据题目、题型和难度进行筛选
        if (Objects.nonNull(asStudyQuestionsEntity.getTopic())) {
            questionQueryWrapper.eq(AsStudyQuestionsEntity::getTopic, asStudyQuestionsEntity.getTopic());
        }
        if (Objects.nonNull(asStudyQuestionsEntity.getQuestionType())) {
            questionQueryWrapper.eq(AsStudyQuestionsEntity::getQuestionType, asStudyQuestionsEntity.getQuestionType());
        }
        if (Objects.nonNull(asStudyQuestionsEntity.getDifficulty())) {
            questionQueryWrapper.eq(AsStudyQuestionsEntity::getDifficulty, asStudyQuestionsEntity.getDifficulty());
        }

        // 查询数据库中的题目
        List<AsStudyQuestionsEntity> questions = studyQuestionsMapper.selectList(questionQueryWrapper);

        if (!questions.isEmpty()) {
            // 2. 查询与题目相关的模块名和考点信息
            questions.forEach(question -> {
                // 查询模块名
                if (Objects.nonNull(question.getModuleId())) {
                    Long moduleId = question.getModuleId();
                    AsModuleEntity module = moduleMapper.selectById(moduleId);
                    if (module != null) {
                        question.setModuleName(module.getModuleName());
                    }
                }

                // 查询考点信息
                if (Objects.nonNull(question.getExamCenterId())) {
                    Long examCenterId = question.getExamCenterId();
                    AsModuleEntity examCenter = moduleMapper.selectById(examCenterId);
                    if (examCenter != null) {
                        question.setExamCenter(examCenter.getExamCenter());
                    }
                }
            });

            // 3. 查询与题目相关的所有选项
            List<Long> questionIds = questions.stream()
                .map(AsStudyQuestionsEntity::getId)
                .collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(questionIds)) {
                LambdaQueryWrapper<AsOptionAnswerEntity> optionQueryWrapper = new LambdaQueryWrapper<>();
                optionQueryWrapper.in(AsOptionAnswerEntity::getTopicId, questionIds);
                List<AsOptionAnswerEntity> options = optionAnswerMapper.selectList(optionQueryWrapper);

                // 将选项映射到各自的题目上
                Map<Long, List<AsOptionAnswerEntity>> optionsMap = options.stream()
                    .collect(Collectors.groupingBy(AsOptionAnswerEntity::getTopicId));

                questions.forEach(question -> {
                    List<AsOptionAnswerEntity> relatedOptions = optionsMap.get(question.getId());
                    question.setOptions(relatedOptions);
                });
            }
        }

        return questions;
    }

    @Override
    @Transactional  // 确保事务管理
    public void addQuestions(AsStudyQuestionsDto asStudyQuestionsDto) {
        // 获取题目实体列表
        List<AsStudyQuestionsEntity> questionsEntityList = asStudyQuestionsDto.getAsStudyQuestionsEntityList();
        List<AsOptionAnswerEntity> optionAnswerEntityList = asStudyQuestionsDto.getAsOptionAnswerEntityList();

        // 遍历题目列表，将每个题目存入数据库，并获取题目的 ID
        for (AsStudyQuestionsEntity question : questionsEntityList) {
            // 设置创建者信息
            question.setCreateBy(LoginHelper.getLoginUser().getUsername());

            // 插入题目并获取生成的题目ID
            studyQuestionsMapper.insert(question);
            Long questionId = question.getId();

            // 根据临时ID (tempTopicId) 过滤出与当前题目相关的选项答案
            String tempTopicId = question.getTempTopicId();
            List<AsOptionAnswerEntity> relatedOptionAnswers = optionAnswerEntityList.stream()
                .filter(optionAnswer -> tempTopicId.equals(optionAnswer.getTempTopicId()))
                .toList();


            List<AsOptionAnswerEntity> asOptionAnswerEntities = new ArrayList<>();
            // 遍历并插入与当前题目相关的选项答案
            for (AsOptionAnswerEntity optionAnswer : relatedOptionAnswers) {
                optionAnswer.setTopicId(questionId);  // 设置关联的题目ID
                asOptionAnswerEntities.add(optionAnswer);
            }
            //批量添加
            optionAnswerService.saveBatch(asOptionAnswerEntities);

        }
    }


}
